﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Zero.UControl.Component.MsgBox;

namespace Zero.UControl.Component
{
    public class LoadingBase : ContentControl
    {
        public LoadingBase()
        {

        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            // 将状态更新放到模板加载之后执行，避免视觉状态切换早于模板加载完成导致首次切换状态时，视觉状态不生效的问题
            UpdateLoading(State);
        }

        public LoadingState State
        {
            get { return (LoadingState)GetValue(StateProperty); }
            set { SetValue(StateProperty, value); }
        }

        public static readonly DependencyProperty StateProperty =
            DependencyProperty.Register("State", typeof(LoadingState), typeof(LoadingBase), new PropertyMetadata(LoadingState.UnLoading, OnPropertyChanged));


        private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {

            LoadingState newValue = (LoadingState)e.NewValue;
            (d as LoadingBase)?.UpdateLoading(newValue);
        }

        private void UpdateLoading(LoadingState newValue)
        {
            switch (newValue)
            {
                case LoadingState.Loading:
                    Visibility = Visibility.Visible;
                    break;
                case LoadingState.UnLoading:
                    Visibility = Visibility.Collapsed;
                    break;
                default:
                    MsgBoxManager.Error("未知的状态类型");
                    break;
            }
            VisualStateManager.GoToState(this, newValue.ToString(), true);
        }
    }
}
